package com.engr.lyx.gateway.biz.filter;

import com.engr.lyx.common.utils.StringUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: blog
 * @description: 请求过滤
 * @author: lyx
 * @create: 2019-06-05
 **/
@Slf4j
@Component
public class TokenFilter extends ZuulFilter {

    /**
     * 过滤器类型
     * pre 请求之前执行filter,
     * route 处理请求，进行路由
     * post 请求处理完后执行的filter
     * error 出现错误执行的filter
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 过滤器顺序，越小越先执行
     * @return
     */
    @Override
    public int filterOrder() {
        return 4;
    }

    /**
     * 过滤器是否生效，返回true代表需要权限校验，false
     * 代表不需要用户校验即可访问
     * @return
     */
    @Override
    public boolean shouldFilter() {

        //共享RequestContext，上下文对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        request.setAttribute("pageNum", "1");
        // 判断需要校验路由
        if (request.getRequestURI().contains("/api1")) {
            return true;
        }
        return false;
    }

    /**
     * 只有shouldFilter方法返回true的时候才会执行
     *
     * @return
     */
    @Override
    public Object run() {

        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        //token对象,有可能在请求头传递过来，也有可能是通过参数传过来，实际开发一般都是请求头方式
        String token = request.getHeader("token");

        log.info("request: {},{},{},", request.getQueryString(), request.getParameterMap(), request.getParameterNames());
        if (StringUtils.isBlank((token))) {
            token = request.getParameter("token");
        }
        System.out.println("页面传来的token值为：" + token);
        //登录校验逻辑  如果token为null，则直接返回客户端，而不进行下一步接口调用
        if (StringUtils.isBlank(token)) {
            // 过滤该请求，不对其进行路由
            requestContext.setSendZuulResponse(false);
            //返回错误代码
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }
        return null;
    }
}
